package com.srwl.mytx.widget;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.florent37.viewanimator.AnimationBuilder;
import com.github.florent37.viewanimator.ViewAnimator;
import com.srwl.mytx.R;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.utils.GlideLoadUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by wei on 2016/6/13.
 */
public class BarrageLayout extends FrameLayout {
    private static final String TAG = "BarrageLayout";
    @BindView(R.id.container1)
    RelativeLayout container1;
    @BindView(R.id.container2)
    RelativeLayout container2;
    @BindView(R.id.container3)
    RelativeLayout container3;
    @BindView(R.id.container4)
    RelativeLayout container4;
//    @BindView(R.id.container5)
//    RelativeLayout container5;

    int count = 0;
    private List<Message> waitShowMesage = new ArrayList<>();
    private List<RelativeLayout> containerList = new ArrayList<>();
    int screenWidth;
    private Context context;

    public BarrageLayout(Context context) {
        super(context);
        this.context = context;
        init(context, null);
    }

    public BarrageLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BarrageLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        init(context, attrs);
    }


    private void init(Context context, AttributeSet attrs) {
        LayoutInflater.from(context).inflate(R.layout.widget_barrage_layout, this);
        ButterKnife.bind(this);
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        screenWidth = displayMetrics.widthPixels;
        containerList.add(container1);
        containerList.add(container2);
        containerList.add(container3);
        containerList.add(container4);
       // containerList.add(container5);
    }

    public synchronized void addBarrage(Message message) {
        //如果有等待消息的 弹幕消息，说明现在跑道拥挤，直接保存进 等待集合，不应该去尝试 “插队”
//        if (waitShowMesage.size() != 0) {
//            waitShowMesage.add(message);
//            return;
//        }
        showBarrage(message);

    }

    private void showBarrage(Message message) {

        ViewGroup targetContainer = selectContainer();


        //  Integer topMargin = getTopMargin();

        //为null 表示没找到合适的 跑道，把该消息保存起来
        if (targetContainer == null) {
            waitShowMesage.add(message);
            return;
        }
        ((Activity) getContext()).runOnUiThread(new Runnable() {
            @Override
            public void run() {

                View barrageView = newBarrageView(message);
                addInParentView(barrageView, targetContainer);
            }
        });
    }

    private ViewGroup selectContainer() {

        Random random=new Random();
        int nextInt = random.nextInt(containerList.size()-1);
        RelativeLayout remove = containerList.remove(nextInt);
        containerList.add(remove);

        for (RelativeLayout relativeLayout : containerList) {
            if (relativeLayout.getChildCount() == 0) {//说明这个容器是空闲的
                Log.d(TAG, "selectContainer: 找到空闲的容器，直接返回");
                return relativeLayout;
            }
        }
        for (RelativeLayout relativeLayout : containerList) {
            int childCount = relativeLayout.getChildCount();
            if (childCount == 0) {
                Log.d(TAG, "selectContainer: 第二次  找到空闲的容器，直接返回");
                return relativeLayout;
            }
            View childAt = relativeLayout.getChildAt(childCount - 1);
            if (childAt != null) {
                int right = (int) (childAt.getRight() + childAt.getTranslationX());
                Log.d(TAG, "selectContainer: childView 右边的位置：" + right);
                Log.d(TAG, "selectContainer: getWidth()" + getWidth());
                if (right < getWidth() - 50) {//说明这条跑道 不会追尾
                    Log.d(TAG, "selectContainer: 炸到不会追尾的的容器，，，，，，，，");
                    return relativeLayout;
                }
            }
        }

        return null;
    }

    private void addInParentView(View barrageView, ViewGroup targetContainer) {
        // LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //  Log.i(TAG, "handleMessage: barrageView.getHeight()" + barrageView.getHeight());
        // int topMargin = (int) ((getHeight() - 150) * Math.random());//这时候没法获取 弹幕的高度，减去150是为了 避免弹幕显示不全，


        //  topMarginMap.put(barrageView, topMargin);
        // layoutParams.topMargin = topMargin;
        targetContainer.addView(barrageView);
        barrageView.measure(0, 0);
        int barrageWidth = barrageView.getMeasuredWidth();
        AnimationBuilder builder = ViewAnimator.animate(barrageView).translationX(getWidth(), -barrageWidth).interpolator(new LinearInterpolator()).duration((long) (7000 + Math.random() * 2000));
        builder.onStop(() -> {
            ViewGroup parent = (ViewGroup) barrageView.getParent();
            if (parent != null) {
                parent.removeView(barrageView);
            }
            checkAndShowBarrage();

        });
        builder.start();
    }

    private synchronized void checkAndShowBarrage() {
        if (waitShowMesage.size() != 0) {
            new Thread(() -> addBarrage(waitShowMesage.remove(0))).start();
        }
    }


    private View newBarrageView(Message message) {
        View barrageView = LayoutInflater.from(getContext()).inflate(R.layout.layout_barrage_show, null);
        TextView nameView = barrageView.findViewById(R.id.title);
        TextView contentView = barrageView.findViewById(R.id.tv_content);
        CircleImageView avatar = barrageView.findViewById(R.id.avatar);
//        try {
//            Glide.with(context).load(message.getIcon()).error(R.drawable.tx_default_avatar).into(avatar);  //    java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        GlideLoadUtils.glideLoad(context,message.getIcon(),avatar,R.drawable.tx_default_avatar_1);
        nameView.setText(message.getTitle());
        contentView.setText(message.getContent());
        return barrageView;
    }
}
